<?php
namespace app\admin\controller;

use think\facade\View;

use app\admin\model\Category as CategoryModel;
use app\admin\model\Article as ArticleModel;

/**
 * 文章管理  
 * @author huwhis@163.com
 * @version   0.0.2
 */
class Article extends Base
{
    public function index($cid = 0)
    {
        $param = $this->app->request->param();

        $cid = isset($param['cid']) ? (int) $param['cid'] : 0;
        
        $key = isset($param['key']) ? (string) $param['key'] : '';

        $list = ArticleModel::queryPage($param);

        $category_model = new CategoryModel();

        $categoryTree = obj_tree($category_model->field('id, pid, name')->select());

        $categories = $category_model->column('name', 'id');

        return View::fetch('index', [
            'categoryTree' => $categoryTree,
            'categories' => $categories,
            'list' => $list,
            'cid' => $cid,
            'key' => $key
        ]);
    }

    public function info($cid = 0, $id = 0)
    {
        if (!$cid) {
            $this->error('请选择栏目');
        }
        if ($id) {
            $data = ArticleModel::find($id);
        } else {
            $data = new ArticleModel();
        }

        $category_info = CategoryModel::field('id, pid, name')->find($cid);

        return View::fetch('save', [
            'cid' => $cid,
            'category_info' => $category_info,
            'data' => $data,
        ]);
    }

    public function save()
    {
        if ($this->app->request->isPost()) {
            $param = $this->app->request->param();
            // var_dump($param);
            // exit;
            if (!$param['cid']) {
                $this->error('请选择栏目');
            }
            if ($param['title'] == '') {
                $this->error("标题不能为空");
            }
            if ($param['content'] == '') {
                $this->error("内容不能为空");
            }

            try {
                if ($param['id'] != 0) {
                   ArticleModel::update($param);
                } else {
                    $param['userid'] = $this->uid;
                    $param['username'] = $this->username;

                    unset($param['id']);
                    ArticleModel::create($param);
                }
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误提示:".$msg);
            }
            $this->success('操作成功', url('article/index', ['cid'=>$param['cid']]));
        }
    }
}
